package com.zhp.ggweather.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import com.zhp.ggweather.R;
import com.zhp.ggweather.model.City;

public class SearchCityAdapter extends BaseAdapter implements Filterable{
	
	private List<City> mAllCities;
	private Context mContext;
	private List<City> mResultCities;
	private LayoutInflater mInflater;
	

	public SearchCityAdapter(List<City> mAllCities, Context mContext) {
		super();
		this.mAllCities = mAllCities;
		this.mContext = mContext;
		mResultCities=new ArrayList<>();
		mInflater=LayoutInflater.from(mContext);
	}

	@Override
	public int getCount() {
		return mResultCities.size();
	}

	@Override
	public City getItem(int position) {
		return mResultCities.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView==null) {
			convertView=mInflater.inflate(R.layout.search_city_item, parent,false);
		}
		TextView tv_province=(TextView) convertView.findViewById(R.id.tv_province);
		TextView tv_city=(TextView) convertView.findViewById(R.id.tv_city);
		tv_province.setText(mResultCities.get(position).getProvince());
		tv_city.setText(mResultCities.get(position).getName());
		return convertView;
	}

	@Override
	public Filter getFilter() {
		Filter filter=new Filter() {
			
			@Override
			protected void publishResults(CharSequence constraint, FilterResults results) {
				mResultCities=(ArrayList<City>) results.values;
				if (results.count>0) {
					notifyDataSetChanged();
				}else {
					notifyDataSetInvalidated();
				}
			}
			
			@Override
			protected FilterResults performFiltering(CharSequence constraint) {
				String str=constraint.toString().toUpperCase();
				FilterResults results=new FilterResults();
				ArrayList<City> cityList=new ArrayList<>();
				if (mAllCities!=null&&mAllCities.size()!=0) {
					for (City city : mAllCities) {
						//匹配全拼、首字母和城市名中文
						if (city.getPy().indexOf(str)>-1
								||city.getPinyin().indexOf(str)>-1
								||city.getName().indexOf(str)>-1) {
							cityList.add(city);
						}
					}
				}
				results.values=cityList;
				results.count=cityList.size();
				return results;
			}
		};
		return filter;
	}

	
	
}
